package com.tiyende.kash.loop.ui.activity

import android.graphics.Color
import android.view.View
import androidx.camera.core.AspectRatio
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageCapture
import androidx.camera.core.ImageCaptureException
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.core.content.ContextCompat
import com.tiyende.kash.loop.R
import com.tiyende.kash.loop.TiyendeApp
import com.tiyende.kash.loop.common.CommonActivity
import com.tiyende.kash.loop.databinding.TiyendeActivityCameraCardBinding
import com.tiyende.kash.loop.event.TiyendeEventPointType
import com.tiyende.kash.loop.request.HttpHelper
import com.tiyende.kash.loop.ui.contract.IViewContract
import com.tiyende.kash.loop.ui.presenter.TiyendeImageUploadPresenter
import com.tiyende.kash.loop.utils.TiyendeImageUtil
import com.tiyende.kash.loop.utils.TiyendeTitleBarUtil
import com.tiyende.kash.loop.utils.imgcovert.ImageConvert
import com.tiyende.kash.loop.utils.log.TiyendeLogger
import java.io.File
import java.util.concurrent.ExecutorService
import java.util.concurrent.Executors


/**
 * TiyendeCredit
 * @Author wwdeng
 * @CreateTime: 2024/11/22 11:15
 * @Annotation：Pan Card 、 Aadhaar Card
 */
class TiyendeCameraCardActivity: CommonActivity(), IViewContract.ITiyendeImageUploadView  {
    private var _binding: TiyendeActivityCameraCardBinding? = null
    private val binding get() = _binding ?: throw IllegalStateException(
        "camera card info binding because it is null. Either the view hasn't been created yet, or it has already been destroyed."
    )

    private var upLoadPresenter: TiyendeImageUploadPresenter? = null

    private var cameraExecutor: ExecutorService? = null
    private var imageCapture: ImageCapture? = null
    private var imgUsePath = ""

    override fun getTiyendeRootView(): View {
        _binding = TiyendeActivityCameraCardBinding.inflate(layoutInflater)
        return binding.root
    }

    override fun initTiyendeView() {
        TiyendeTitleBarUtil.setStatusBarLightMode(this, false)
        _binding?.cameraTitleLayout?.setPadding(0, TiyendeTitleBarUtil.getStatusBarHeight(),0,0)

        startCameraOcr()
    }

    override fun initTiyendeListener() {
        _binding?.imgCameraBack?.setOnClickListener{
            finish()
        }

        _binding?.imgCameraCustomer?.setOnClickListener{
            val eventTitle = takeCameraPageName()
            showCustomerDialog(eventTitle)
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CUSTOMER,eventTitle)
        }
        //切换语言
        _binding?.imgCameraLanguage?.setOnClickListener {
            val eventTitle = takeCameraPageName()
            showTiyendeSwitchLanguageDialog(eventTitle,onConfirmCallback = {
            })
        }

        //拍照
        _binding?.imgCameraTake?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_TAKE_PHOTO,takeCameraPageName())
            takeCameraOcrFilePhoto()
        }

        //重拍
        _binding?.cameraRemakeLayout?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_REMAKE_PHOTO,takeCameraPageName())
            showCameraOcrTakeView()
        }

        //使用
        _binding?.cameraUseLayout?.setOnClickListener{
            addEventPointRequestAction(TiyendeEventPointType.CLICK.TIYENDE_CLICK_CAMERA_USE_PHOTO,takeCameraPageName())

            showTiyendeLoading(isTOuchOut = false, isCancel = false)
            if (upLoadPresenter == null){
                upLoadPresenter = TiyendeImageUploadPresenter(this)
            }
            if (imgUsePath.isNotEmpty()){
                upLoadPresenter?.submitUploadImageAction(imgUsePath)
            }
        }
    }

    override fun loadTiyendeData() {
    }

    /**
     * 打开相机预览
     */
    private fun startCameraOcr() {
        showCameraOcrTakeView()
        cameraExecutor = Executors.newSingleThreadExecutor()
        val cameraProviderFuture = ProcessCameraProvider.getInstance(this)
        cameraProviderFuture.addListener(Runnable {
            val cameraProvider: ProcessCameraProvider = cameraProviderFuture.get()
            val preview = Preview.Builder()
                .setTargetAspectRatio(AspectRatio.RATIO_16_9)
                .build()
                .also {
                    it.setSurfaceProvider(_binding?.cameraPreView?.surfaceProvider)
                }
            imageCapture = ImageCapture.Builder().build()
            //打开后置摄像头
            val cameraSelector = CameraSelector.DEFAULT_BACK_CAMERA
            try {
                cameraProvider.unbindAll()
                cameraProvider.bindToLifecycle(this, cameraSelector, preview,imageCapture)
            } catch(exc: Exception) {
            }
        }, ContextCompat.getMainExecutor(this))
    }

    /**
     * 拍照并保存到本地
     */
    private fun takeCameraOcrFilePhoto(){
        if (imageCapture != null){
            //创建文件
            val filePath = TiyendeApp.app.filesDir.absolutePath
            val outputFile = File(filePath,"${System.currentTimeMillis()}.jpg")
            if (!outputFile.exists()){
                outputFile.mkdir()
            }
            //创建输出选项对象
            val metadata = ImageCapture.Metadata()
            metadata.isReversedHorizontal = false
            //创建文件
            val outputFileOptions = ImageCapture.OutputFileOptions.Builder(outputFile)
                .setMetadata(metadata)
                .build()
            //开始拍照
            imageCapture?.takePicture(outputFileOptions, ContextCompat.getMainExecutor(this),object : ImageCapture.OnImageSavedCallback{
                override fun onImageSaved(outputFileResults: ImageCapture.OutputFileResults) {
                    val imgUri = outputFileResults.savedUri
                    TiyendeLogger.e("take photo complete>>>>>>>${imgUri?.path}")
                    // 图片处理
                    ImageConvert.covert(context = this@TiyendeCameraCardActivity, uri = imgUri) { localPath, bitmap ->
                        if (localPath != null){
                            imgUsePath = localPath
                            TiyendeLogger.e("imageConvert success>>>>>>>$localPath")
                            showCameraOcrCompleteView()
                        }
                    }
                }
                override fun onError(exception: ImageCaptureException) {
                    TiyendeLogger.e("take photo failed>>>>>>>${exception.message}")
                }
            })
        }
    }

    /**
     * 显示拍照样式
     */
    private fun showCameraOcrTakeView(){
        _binding?.let { binding ->
            binding.cameraMaskView.setMaskColor(Color.parseColor("#80000000"))
            binding.imaCameraPreview.visibility = View.GONE
            binding.imgCameraTake.visibility = View.VISIBLE
            binding.cameraUseLayout.visibility = View.GONE
            binding.cameraRemakeLayout.visibility = View.GONE
        }
    }

    /**
     * 显示拍照完成页面
     */
    private fun showCameraOcrCompleteView(){
        _binding?.let { binding ->
            TiyendeImageUtil.instance?.loadImageUrl(this@TiyendeCameraCardActivity,binding.imaCameraPreview,imgUsePath)
            binding.cameraMaskView.setMaskColor(getColor(R.color.black))
            binding.imaCameraPreview.visibility = View.VISIBLE
            binding.imgCameraTake.visibility = View.GONE
            binding.cameraUseLayout.visibility = View.VISIBLE
            binding.cameraRemakeLayout.visibility = View.VISIBLE
        }
    }

    /**
     * 图片上传完成
     */
    private fun showTiyendeUploadImageSuccess(imgPath: String, imgUrl: String) {
        hiddenTiyendeLoading()
        val intent = intent
        intent.putExtra("imgLocalPath",imgPath)
        intent.putExtra("imgUrl",imgUrl)
        setResult(RESULT_OK,intent)
        finish()
    }

    /**
     * 获取页面名称
     */
    private fun takeCameraPageName(): String{
        var eventRemark = ""
        intent.extras?.let {
            eventRemark = it.getString("pageName","Card Step")
        }
        return eventRemark
    }

    /**
     * 图片上传完成
     */
    override fun showTiyendeImageUploadSuccess(imgPath: String, imgUrl: String) {
        showTiyendeUploadImageSuccess(imgPath,imgUrl)
    }

    override fun onStart() {
        super.onStart()
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_CARD_CAMERA_START,takeCameraPageName())
    }

    override fun onDestroy() {
        super.onDestroy()
        _binding = null
        HttpHelper.cancelTag(this)
        addEventPointRequestAction(TiyendeEventPointType.PAGE.TIYENDE_PAGE_STEP_CARD_CAMERA_END,takeCameraPageName())
        cameraExecutor?.shutdown()
    }
}